package com.tticar.invmanager.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.tticar.invmanager.common.utils.MyResponseBody;
import com.tticar.invmanager.common.utils.PinYinUtil;
import com.tticar.invmanager.entity.CarBrand;
import com.tticar.invmanager.entity.vo.MyPage;
import com.tticar.invmanager.entity.vo.Tree;
import com.tticar.invmanager.service.ICarBrandService;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 车品牌 前端控制器
 * </p>
 *
 * @author joeyYan
 * @since 2018-09-18
 */
@Controller
@RequestMapping("/carBrand")
public class CarBrandController extends BaseController {

    @Autowired
    private ICarBrandService carBrandService;

    private static Logger logger = LoggerFactory.getLogger(CarBrandController.class);
    private static final char[] letters = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};

    @GetMapping("pinyin")
    @ResponseBody
    public String pinyin() {
        Wrapper wrapper = new EntityWrapper();
        wrapper.in("level", new Integer[]{1,2,3});
        List<CarBrand> list = this.carBrandService.selectList(wrapper);
        for(CarBrand brand : list) {
            brand.setInitials(PinYinUtil.getFirstLettersUp(brand.getName()));
        }
        this.carBrandService.updateBatchById(list);
        return "success";
    }

    @GetMapping("crawler")
    @ResponseBody
    public String crawler() throws Exception {
        if(1 == 1) {
            return "false";
        }
        long count = 1;
        for (char letter : letters) {
            Document html = Jsoup.connect("https://www.autohome.com.cn/grade/carhtml/" + letter + ".html").get();
            Elements dls = html.select("dl");

            List<CarBrand> list = new ArrayList<>();
            for (Element brandEt : dls) {
                String brandName = brandEt.select("dt > div > a").first().text();
                String logo = "http:" + brandEt.select("dt > a > img").first().attr("src");
                logger.info("品牌:" + brandName);
                logger.info("logo:" + logo);

                CarBrand b1 = new CarBrand();
                b1.setPid(0l);
                b1.setName(brandName);
                b1.setLogo(logo);
                b1.setInitial(PinYinUtil.getFirstLettersUp(brandName).substring(0, 1));
                b1.setLevel(1);
                b1.setId(count++);
                list.add(b1);

                Elements subBrandEts = brandEt.select("dd > .h3-tit");
                for (Element subBrandEt : subBrandEts) {
                    String subBrandName = subBrandEt.text();
                    logger.info("子品牌:" + subBrandName);
                    CarBrand b2 = new CarBrand();
                    b2.setPid(b1.getId());
                    b2.setName(subBrandName);
                    b2.setLevel(2);
                    b2.setId(count++);
                    list.add(b2);

                    Elements serialEts = subBrandEt.nextElementSibling().select("li > h4 > a");
                    for (Element serialEt : serialEts) {
                        String serial = serialEt.text();
                        logger.info("系列:" + serial);

                        CarBrand b3 = new CarBrand();
                        b3.setPid(b2.getId());
                        b3.setName(serial);
                        b3.setLevel(3);
                        b3.setId(count++);
                        list.add(b3);

                        Document serialDetail = Jsoup.parse(new URL("https:" + serialEt.attr("href")), 1000 * 60);

                        for (int i = 2; i <= 3; i++) {
                            Element wrap = serialDetail.getElementById("specWrap-" + i);
                            if (wrap == null) {//都是停售款时页面不同，https://www.autohome.com.cn/19/#pvareaid=2042208
                                Elements carDetails = serialDetail.getElementsByClass("car_detail");
                                for (Element carDetail : carDetails) {
                                    String modelName = carDetail.select(".models > .header > .car_price > .years").text();
                                    logger.info("车型：" + modelName);
                                    CarBrand b4 = new CarBrand();
                                    b4.setPid(b3.getId());
                                    b4.setName(modelName);
                                    b4.setLevel(4);
                                    b4.setId(count++);
                                    list.add(b4);

                                    Element modelswrap = carDetail.select(".models > .modelswrap").get(1);

                                    //左边
                                    Elements trs = modelswrap.select(".tabwrap > .modtab1 > table > tbody > tr");
                                    for (Element tr : trs) {
                                        String skuName = tr.getElementsByTag("td").first().select("div > a").text();
                                        logger.info("车款：" + skuName);
                                        CarBrand b5 = new CarBrand();
                                        b5.setPid(b4.getId());
                                        b5.setName(skuName);
                                        b5.setLevel(5);
                                        b5.setId(count++);
                                        list.add(b5);
                                    }

                                    //右边
                                    Elements trs2 = modelswrap.select(".tabwrap > .modtab2 > table > tbody > tr");
                                    for (Element tr : trs2) {
                                        String skuName = tr.getElementsByTag("td").first().select("div > a").text();
                                        logger.info("车款：" + skuName);
                                        CarBrand b5 = new CarBrand();
                                        b5.setPid(b4.getId());
                                        b5.setName(skuName);
                                        b5.setLevel(5);
                                        b5.setId(count++);
                                        list.add(b5);
                                    }
                                }
                            } else { //正常页面
                                Elements dls2 = wrap.getElementsByTag("dl");
                                for (Element dl : dls2) {
                                    String modelName = dl.select("dt > .spec-name span").first().text();
                                    logger.info("车型：" + modelName);

                                    CarBrand b4 = new CarBrand();
                                    b4.setPid(b3.getId());
                                    b4.setName(modelName);
                                    b4.setLevel(4);
                                    b4.setId(count++);
                                    list.add(b4);

                                    Elements dds = dl.getElementsByTag("dd");
                                    for (Element dd : dds) {
                                        String skuName = dd.select(".spec-name > .name-param p a").text();
                                        logger.info("车款：" + skuName);

                                        CarBrand b5 = new CarBrand();
                                        b5.setPid(b4.getId());
                                        b5.setName(skuName);
                                        b5.setLevel(5);
                                        b5.setId(count++);
                                        list.add(b5);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            if (list.size() > 0) {
                this.carBrandService.insertBatch(list);
            }
        }

        return "success";
    }

    @PostMapping
    @ResponseBody
    public MyResponseBody post(CarBrand carBrand) {
        carBrandService.insertOrUpdate(carBrand);
        return MyResponseBody.success();
    }

    @PostMapping("delete")
    @ResponseBody
    public MyResponseBody delete(@RequestParam("ids[]") List<Long> ids) {
        MyResponseBody responseBody = MyResponseBody.success();
        carBrandService.delete(ids);
        return responseBody;
    }

    @GetMapping("{id}")
    @ResponseBody
    public MyResponseBody get(@PathVariable("id") Long id) {
        MyResponseBody responseBody = MyResponseBody.success();
        responseBody.setData(carBrandService.selectById(id));
        return responseBody;
    }

    @GetMapping("edit")
    public String edit(CarBrand carBrand, ModelMap modelMap) {
        modelMap.put("id", carBrand.getId());
        return "/carBrand/carBrand_edit";
    }

    @GetMapping("list")
    @ResponseBody
    public Page list(CarBrand carBrand, MyPage<CarBrand> page) {
        return carBrandService.selectPage(carBrand, page);
    }

    @GetMapping
    public String index() {
        return "/carBrand/carBrand";
    }

    @GetMapping("tree")
    public String tree(Integer isCheck, ModelMap modelMap) {
        modelMap.put("isCheck", isCheck == null ? 1 : isCheck);
        return "/carBrand/carBrandTree";
    }

    @PostMapping("/tree")
    @ResponseBody
    public List<Tree> tree(Long id, String searchText) {
        if ((id == null || id == 0) && StringUtils.isNotBlank(searchText)) {
            return carBrandService.tree(searchText);
        }else {
            return carBrandService.tree(id);
        }
    }

}
